const jwt = require("jsonwebtoken")

const SecretKey = require("../models/config").SecretKey

module.exports = async (ctx, next) => {
        
            let token = ctx.request.header.authorization
            let path = ctx.url
            let reg = /^(\/admin)/
            let isport =  reg.test( path )
            if ( !isport ) {
                await  next()
            } else {
                try {
                    if (token) {
                        let payLoad = jwt.verify(token, SecretKey)
                         
                        let now = new Date().getTime() / 1000
                        if (now > payLoad.exp) {
                            ctx.status = 401
                            ctx.body = {
                                code: 401,
                                msg: "token过期"
                            }
                        } else {
                            ctx.state.user = {
                                id: payLoad.id,
                            }
                            await next()
                        }
                        
                    } else {
                        ctx.status = 401
                        ctx.body = {
                            code: 401,
                            msg: "token不存在,认证失败"
                        }
                    }
                } catch (error) {
                    ctx.status = 403
                        ctx.body = {
                            code: 403,
                            msg: "登录过期,请重新登录"
                        }
                }
            }
       
}